package com.uriuniv.dao;

import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

import com.uriuniv.domain.Board;
import com.uriuniv.domain.BoardArticle;
import com.uriuniv.mapper.BoardArticleM;
import com.uriuniv.mapper.BoardM;

public class BoardArticleD {

	private JdbcTemplate jdbcTemplate;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public List<BoardArticle> getBoardArtcileList(String srchWord, int pageNum, String boardId, String[] univId){
		
		int perPageCount = 15;
		int last = pageNum * perPageCount;
		int first = last - (perPageCount - 1);
		
		String BOARD_ARTICLE_LIST = "SELECT * FROM BOARD_ARTICLE WHERE (TITLE LIKE '%" + srchWord + "%' OR NAME LIKE '%" + srchWord + "%') AND BOARD_ID LIKE '%" + boardId + "%'";
			
		if(univId.length != 0){
			
			BOARD_ARTICLE_LIST += " AND UNIV_ID IN (";
			
			for(int i=0; i<univId.length; i++){
				BOARD_ARTICLE_LIST += "'" + univId[i] + "'";
				if(i != univId.length-1){
					BOARD_ARTICLE_LIST += ", ";
				}
			}
			
			BOARD_ARTICLE_LIST += ")";
			
		}
		
		BOARD_ARTICLE_LIST += " ORDER BY REG_DATE DESC";
		
		final String BOARD_ARTICLE_LIST_PAGGING = "SELECT * FROM (" + 
											"SELECT ROWNUM AS RNUM, A.* FROM (" + 
													BOARD_ARTICLE_LIST + 
											") A WHERE ROWNUM <= " + last +  
										   ") WHERE RNUM >= " + first;		
		
		List<BoardArticle> list = (List<BoardArticle>)jdbcTemplate.query(BOARD_ARTICLE_LIST_PAGGING, new BoardArticleM());
		
		return list;
	}
	
	public int getBoardArticleCount(){
		final String BOARD_ARTICLE_COUNT = "SELECT COUNT(*) FROM BOARD_ARTICLE";
		int count = jdbcTemplate.queryForInt(BOARD_ARTICLE_COUNT);
		return count;
	}
	
	public List<Board> getBoardList(){
		
		final String BOARD_LIST = "SELECT * FROM BOARD ORDER BY order_no";
		
		List<Board> boardList = (List<Board>)jdbcTemplate.query(BOARD_LIST, new BoardM());
		
		return boardList;
	}
	
	
}
